Aggregate Functions And Loops In Sql Server